package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.entity.SiteInfo;

/**
 * 地图模式
 * @author kuanter
 *
 */
@Deprecated
public class MapSites extends Activity {
	static LinearLayout tip;  //提示位置到网点的距离
	static TextView toSiteDistance;  //距离
	static TextView need_time;  //须花费时间
	static int speed = 30;
	static ProApplication application;
	
	static MapView mMapView = null;


	public MKMapViewListener mMapListener = null;
	FrameLayout mMapViewContainer = null;

	EditText indexText = null;
	MyLocationOverlay myLocationOverlay = null;
	static int index = -1;

	double pi = 3.1415926;
	// overlay半径
	int r = 50000;

	boolean setCenter = false;

	LayoutInflater factory;

	static View mPopView;

	static TextView popviewTitle = null;
	static ImageView popviewSubTitle = null;
	static TextView tv_distance = null;
	static ImageView imageView10;
	static TextView pop_site_id;


	static boolean animation = false;

	PopupWindow mPopWindow;

	int zoomLevel = 16;
	ProgressDialog progressDialog;
	
	ImageButton left_arrow;
	ImageButton right_arrow;
	TextView from_to;
	

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				// overlay 数量
				/*
				 * for (int i=0; i<iSize ; i++){ // int lat = (int) (cLat +
				 * r*Math.cos(2*i*pi/iSize)); // int lon = (int) (cLon +
				 * r*Math.sin(2*i*pi/iSize)); int lat = (int)((locData.latitude)
				 * * 1E6); int lon = (int)((locData.longitude) * 1E6);
				 * OverlayItem item= new OverlayItem(new
				 * GeoPoint(lat,lon),"item"+i,"item"+i);
				 * item.setMarker(res.get(i%(res.size()))); mGeoList.add(item);
				 * }
				 */

				int lat = (int) ((ProApplication.getInstance().locData.latitude) * 1E6);
				int lon = (int) ((ProApplication.getInstance().locData.longitude) * 1E6);
				// OverlayItem item= new OverlayItem(new
				// GeoPoint(lat,lon),"1","1");
				// item.setMarker(res.get(0));
				// mGeoList.add(item);

				if (!setCenter) {
					mMapView.refresh();
					mMapView.getController().setCenter(new GeoPoint(lat, lon));
					setCenter = true;
				}
			} else if(msg.what == ProApplication.location_cuccess) {
				if(mPopView !=null) {
					mPopView.setVisibility(View.GONE);  //首先去掉弹出窗口
				}
				if(tip != null) {
					tip.setVisibility(View.GONE);
				}
				
				if(mMapView != null) {
					myLocationOverlay.setData(ProApplication.getInstance().locData);
					if(mMapView != null && mMapView.getOverlays() != null) {
						mMapView.getOverlays().add(myLocationOverlay);
					}
					double latitude = ProApplication.getInstance().locData.latitude;
					double longtitude = ProApplication.getInstance().locData.longitude;
					List<GeoPoint> list = new ArrayList<GeoPoint>();  //用来排序的list
					GeoPoint myPoint = new GeoPoint((int)(latitude * 1E6), (int)(longtitude * 1E6));
					list.add(myPoint);
					
					if(currentPage == 1) {
						left_arrow.setVisibility(View.INVISIBLE);
					} else if(currentPage == totalPage) {
						right_arrow.setVisibility(View.INVISIBLE);
					} else {
						left_arrow.setVisibility(View.VISIBLE);
						right_arrow.setVisibility(View.VISIBLE);
					}
					
					if(currentPage == totalPage) {
						from_to.setText(((currentPage - 1) * pageSum + 1) + "-" + sum + "家");
					} else {
						from_to.setText(((currentPage - 1) * pageSum + 1) + "-" + currentPage * pageSum + "家");
						
					}
					
					int i = 0;
					mGeoList.clear();
					mMapView.getOverlays().clear();
					
					
					for(SiteInfo site : mapSiteList) {
						if(i < currentPage * pageSum && i >= (currentPage - 1) * pageSum) {
							GeoPoint point = site.getPoint();
							OverlayItem overlayItem = new OverlayItem(point, i+"", site.getSiteName());
							overlayItem.setMarker(res.get(0));
							mGeoList.add(overlayItem);
							list.add(point);
						}
						i++;
					}
					
					Drawable marker = MapSites.this.getResources().getDrawable(
							R.drawable.green);
					
					ov = new OverlayTest1(marker, MapSites.this);
//					ov.removeAll();
					
					for (OverlayItem item1 : mGeoList) {
						ov.addItem(item1);
					}
					mMapView.getOverlays().add(ov);
					
					OverlayItem myLocation = new OverlayItem(new GeoPoint((int)(latitude * 1E6), (int)(longtitude * 1E6)), "my", "my");
					myLocation.setMarker(res.get(1));
					mGeoList.add(myLocation);
					ov.addItem(myLocation);
					
					mMapView.refresh();
					
					fitPoints(list);
				}
			}
		};
	};
	
	private void fitPoints(List<GeoPoint> points) {
	    // set min and max for two points
	    int nwLat = -90 * 1000000;
	    int nwLng = 180 * 1000000;
	    int seLat = 90 * 1000000;
	    int seLng = -180 * 1000000;
	    // find bounding lats and lngs
	    for (GeoPoint point : points) {
	        nwLat = Math.max(nwLat, point.getLatitudeE6());
	        nwLng = Math.min(nwLng, point.getLongitudeE6());
	        seLat = Math.min(seLat, point.getLatitudeE6());
	        seLng = Math.max(seLng, point.getLongitudeE6());
	    }
	    GeoPoint center = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2);
	    // add padding in each direction
	    final int spanLatDelta = (int) (Math.abs(nwLat - seLat) * 1.1);
	    final int spanLngDelta = (int) (Math.abs(seLng - nwLng) * 1.1);
//	    int spanLatDelta = nwLat - seLat;
//	    int spanLngDelta = seLng - nwLng;

	    // fit map to points
	    mMapView.getController().animateTo(center);
//	    mMapView.getController().zoomToSpan(spanLatDelta, spanLngDelta);
	    mHandler.postDelayed(new Runnable() {
    		@Override
    		public void run() {
    			mMapView.getController().zoomToSpan(spanLatDelta, spanLngDelta);
    			finishProgress();
    		}
    	}, 1000);
	    
	    
	}

	// 存放overlayitem
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	// 存放overlay图片
	public List<Drawable> res = new ArrayList<Drawable>();
	
	OverlayTest1 ov;//覆盖物
	
	boolean sendMessage = false;
	
	static List<SiteInfo> mapSiteList;	//当前数据的list
	int currentPage = 1;	//当前页
	int pageSum = 10;	//一页显示数据数量
	int sum = 25;		//总数据
	int totalPage;   //总页数
	
	RelativeLayout map_top;
	LinearLayout map_chose_service;
	TextView serviceName;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		application = (ProApplication) getApplication();
		if (application.mBMapManager == null) {
			application.mBMapManager = new BMapManager(this);
			application.mBMapManager.init(ProApplication.strKey,
					new ProApplication.MyGeneralListener());
		}
		if(application.locData == null) {
			application.startRequest(mHandler);
		} else {
			sendMessage = true;
		}
		
		setContentView(R.layout.activity_locationoverlay);
		mMapView = (MapView) findViewById(R.id.bmapView);
		
		if(sum % pageSum == 0) {
			totalPage = sum/pageSum;
		} else {
			totalPage = sum/pageSum + 1;
		}
		
		mapSiteList = SitesActivity.getCurrentData();
		
		initMapView();
		
		showProgress("正在加载数据...");


		mMapView.getController().setZoom(zoomLevel);
		mMapView.getController().enableClick(true);

		mMapView.setBuiltInZoomControls(false);  //去掉缩放控件

		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				if (mPopView != null) {
					mPopView.setVisibility(View.GONE);
				}
			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null) {
					title = mapPoiInfo.strText;
					// Toast.makeText(LocationOverlayDemo.this,title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				if (animation) {
					MapSites.mPopView.setVisibility(View.VISIBLE);
					animation = false;
				}
			}

		};
		mMapView.regMapViewListener(ProApplication.getInstance().mBMapManager,
				mMapListener);
		myLocationOverlay = new MyLocationOverlay(mMapView);
//		myLocationOverlay.enableCompass();
		/*myLocationOverlay.setData(ProApplication.getInstance().locData);
		mMapView.getOverlays().add(myLocationOverlay);*/
//		mMapView.refresh();

		res.add(getResources().getDrawable(R.drawable.green));
//		res.add(getResources().getDrawable(R.drawable.red));

		 

		factory = getLayoutInflater();
		mPopView = factory.inflate(R.layout.popview, null);
		popviewTitle = (TextView) mPopView.findViewById(R.id.title);
		TextPaint paint = popviewTitle.getPaint();
		paint.setFakeBoldText(true);
		popviewSubTitle = (ImageView) mPopView.findViewById(R.id.subtitle);
		tv_distance = (TextView) mPopView.findViewById(R.id.tv_distance);
		imageView10 = (ImageView) mPopView.findViewById(R.id.imageView10);
		pop_site_id = (TextView) mPopView.findViewById(R.id.pop_site_id);
		
		mMapView.addView(mPopView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));
		mPopView.setVisibility(View.GONE);
		mPopView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				TextView tv_site_id = (TextView) mPopView.findViewById(R.id.pop_site_id);
				String site_id = tv_site_id.getText().toString();
				if(site_id != null && !site_id.equals("")) {
					Intent intent = new Intent(MapSites.this, MerchantActivity.class);
					intent.putExtra("siteID", site_id);
					intent.putExtra("sitePosition", index);
					startActivity(intent);
					
				}
			}
		});

		mMapView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mPopView != null) {
					mPopView.setVisibility(View.GONE);
					tip.setBackgroundColor(Color.parseColor("#00000000"));
					tip.setVisibility(View.INVISIBLE);
				}
				return false;
			}
		});
		
		if(sendMessage) {
			mHandler.sendEmptyMessage(ProApplication.location_cuccess);
			sendMessage = false;
		}

	}
	
	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		finishProgress();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	//初始化地图模式上面的距离view
	private void initMapView() {
		mMapView.setLongClickable(true);
		// mMapController.setMapClickEnable(true);
		// mMapView.setSatellite(false);
		
		tip = (LinearLayout) findViewById(R.id.tip);
		toSiteDistance = (TextView) findViewById(R.id.toSiteDistance);
		need_time = (TextView) findViewById(R.id.need_time);
		
		left_arrow = (ImageButton) findViewById(R.id.left_arrow);
		left_arrow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				currentPage--;
				if(currentPage <= 0) {
					currentPage = 1;
				}
				mHandler.sendEmptyMessage(ProApplication.location_cuccess);
			}
		});
		
		right_arrow = (ImageButton) findViewById(R.id.right_arrow);
		right_arrow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				currentPage++;
				if(currentPage >= totalPage) {
					currentPage = totalPage;
				}
				mHandler.sendEmptyMessage(ProApplication.location_cuccess);
			}
		});
		
		from_to = (TextView) findViewById(R.id.form_to);
		
		map_top = (RelativeLayout) findViewById(R.id.layTitleBar_wd);
		map_chose_service = (LinearLayout) map_top.findViewById(R.id.map_chose_service);
		serviceName = (TextView) map_top.findViewById(R.id.map_serviceName);
		
		Intent intent = getIntent();
		String serviceName_text = intent.getStringExtra("serviceName");
		serviceName.setText(serviceName_text);
		
		map_chose_service.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
		
		
	}
	
	public void exit(View view) {
		finish();
	}
	
	protected void showProgress(String message) {
		progressDialog = new ProgressDialog(MapSites.this);
		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progressDialog.setMessage(message);
		progressDialog.show();
	}
	
	/**
	 * 结束进度框
	 * 
	 * @param progress
	 */
	protected void finishProgress() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog=null;
		}
	}

}

class OverlayTest1 extends ItemizedOverlay<OverlayItem> {
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Context mContext = null;
	static PopupOverlay pop = null;

	Toast mToast = null;

	public OverlayTest1(Drawable marker, Context context) {
		super(marker);
		this.mContext = context;
		pop = new PopupOverlay(MapSites.mMapView,
				new PopupClickListener() {

					@Override
					public void onClickedPopup(int index) {
						if (null == mToast)
							mToast = Toast.makeText(mContext, "popup item :"
									+ index + " is clicked.",
									Toast.LENGTH_SHORT);
						else
							mToast.setText("popup item :" + index
									+ " is clicked.");
						mToast.show();
					}
				});
		populate();

	}

	GeoPoint prePoint;  //表示是前一个地理位置，当第二次点击的地点位置没改变时不会触发animation，所以弹出不了popwindow，一次在这判断两次位置，若相同，在显示popwindow
	int i = 0;
	protected boolean onTap(int index) {
		/*if (null == mToast)
			mToast = Toast.makeText(mContext, mGeoList.get(index).getTitle(),
					Toast.LENGTH_SHORT);
		else
			mToast.setText(mGeoList.get(index).getTitle());
		mToast.show();*/
		String title = mGeoList.get(index).getTitle();
		if(!title.equals("my")) {
			int location = Integer.valueOf(title);
			MapSites.index = location;
			if(MapSites.mapSiteList != null) {
				SiteInfo site = MapSites.mapSiteList.get(location);
				MapSites.popviewTitle.setText(site.getSiteName());
				MapSites.tv_distance.setText("价格: "+ site.getMaxServicePrice() + "元/次");
				MapSites.tv_distance.setVisibility(View.VISIBLE);
				MapSites.popviewSubTitle.setVisibility(View.VISIBLE);
				MapSites.imageView10.setVisibility(View.VISIBLE);
				MapSites.pop_site_id.setText(site.getId() + "");
			}
		} else {
			MapSites.popviewTitle.setText("我的位置");
			MapSites.tv_distance.setVisibility(View.GONE);
			MapSites.popviewSubTitle.setVisibility(View.GONE);
			MapSites.imageView10.setVisibility(View.GONE);
			MapSites.pop_site_id.setText("");
		}
		

		// 更新气泡位置,并使之显示
		GeoPoint pt = mGeoList.get(index).getPoint();
		MapSites.mMapView.updateViewLayout(
				MapSites.mPopView, new MapView.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						pt, 0,
						0 - MapSites.mPopView.getHeight() / 3,
						MapView.LayoutParams.BOTTOM_CENTER));

		if(MapSites.application.locData != null && !title.equals("my")) {
			float[] distance = new float[1];
			Location.distanceBetween(MapSites.application.locData.latitude, MapSites.application.locData.longitude, mGeoList.get(index).getPoint().getLatitudeE6()/1000000.00, mGeoList.get(index).getPoint().getLongitudeE6()/1000000.00, distance);
			int km = (int) (distance[0] / 1000);
			int minute = (km * 60) / MapSites.speed;
			if(km == 0) {
				MapSites.toSiteDistance.setText("<1KM");
				MapSites.need_time.setText("1分钟");
				MapSites.tip.setVisibility(View.VISIBLE);
				MapSites.tip.setBackgroundColor(Color.BLACK);
			} else {
				MapSites.need_time.setText(minute + "分钟");
				MapSites.tip.setVisibility(View.VISIBLE);
				MapSites.tip.setBackgroundColor(Color.BLACK);
				MapSites.toSiteDistance.setText(km + "KM");
			}
		}
		
		if(i == 0) {
			prePoint = mGeoList.get(index).getPoint();
		}
		if(prePoint.getLatitudeE6() == mGeoList.get(index).getPoint().getLatitudeE6() && prePoint.getLongitudeE6() == mGeoList.get(index).getPoint().getLongitudeE6()) {
			MapSites.mPopView.setVisibility(View.VISIBLE);
		} else {
			prePoint = mGeoList.get(index).getPoint();
		}
		MapSites.mMapView.getController().animateTo(
				mGeoList.get(index).getPoint());
		
		
//		 MapSites.mPopView.setVisibility(View.VISIBLE);
		MapSites.animation = true;
		i++;
		return true;
	}

	public boolean onTap(GeoPoint pt, MapView mapView) {
		if (MapSites.mPopView != null) {
			MapSites.mPopView.setVisibility(View.GONE);
			MapSites.tip.setBackgroundColor(Color.parseColor("#00000000"));
			MapSites.tip.setVisibility(View.INVISIBLE);
		}
		super.onTap(pt, mapView);
		return false;
	}

	@Override
	protected OverlayItem createItem(int i) {
		return mGeoList.get(i);
	}

	@Override
	public int size() {
		return mGeoList.size();
	}

	public void addItem(OverlayItem item) {
		mGeoList.add(item);
		populate();
	}

	public void removeItem(int index) {
		mGeoList.remove(index);
		populate();
	}
	
	public void removeAll() {
		mGeoList.clear();
	}
	
}
